var ToolRepairDelegationTableInit = function () {
    var oTableInit = {};
    //初始化Table
    oTableInit.Init = function () {
        $('#toolRepairDelegationTable').bootstrapTable({
            url: ctx + '/tool/repair/getToolRepairByFilter/get.mvc',         //请求后台的URL（*）
            method: 'get',                      //请求方式（*）
//            toolbar: '#toolbar',                //工具按钮用哪个容器
            striped: true,                      //是否显示行间隔色
            cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
            pagination: true,                   //是否显示分页（*）
            paginationLoop: false,
            sortable: true,                     //是否启用排序
            sortOrder: "asc",                   //排序方式
            queryParams: oTableInit.queryParams,//传递参数（*）
            sidePagination: "server",           //分页方式：client客户端分页，server服务端分页（*）
            pageNumber: 1,                       //初始化加载第一页，默认第一页
            pageSize: 10,                       //每页的记录行数（*）
            pageList: [10, 25, 50, 100],        //可供选择的每页的行数（*）
            search: false,                       //是否显示表格搜索，此搜索是客户端搜索，不会进服务端，所以，个人感觉意义不大
            strictSearch: true,
            showColumns: false,                  //是否显示所有的列
            showRefresh: false,                  //是否显示刷新按钮
            minimumCountColumns: 2,             //最少允许的列数
            clickToSelect: true,                //是否启用点击选中行
            height: 500,                        //行高，如果没有设置height属性，表格自动根据记录条数觉得表格高度
            uniqueId: "pkId",                     //每一行的唯一标识，一般为主键列
            showToggle: false,                    //是否显示详细视图和列表视图的切换按钮
            cardView: false,                    //是否显示详细视图
            detailView: false,                   //是否显示父子表
            singleSelect: false,                    //禁止多选
            checkboxHeader: true,                 //列头取消多选
            columns: [
                {
                    checkbox: true,
                    align: 'center',
                    valign: 'middle'
                },
                {
                    title: '序号',
                    align: 'center',
                    valign: 'middle',
                    formatter: function (value, row, index) {
                        var options = $('#toolRepairDelegationTable').bootstrapTable('getOptions');
                        return options.pageSize * (options.pageNumber - 1) + index + 1;
                    }
                }, {
                    field: 'repairStatus',
                    title: '维修状态',
                    sortable: false,
                    align: 'center',
                    valign: 'middle',
                    formatter: function (value, row, index) {
                        if(value === '2') {
                            return '待审批'
                        }else if (value ==='1') {
                            return "待送修"
                        } else if (value === '5'){
                            return "待返厂"
                        }
                    }
                }, {
                    field: 'toolCode',
                    title: '工装编码',
                    sortable: false,
                    align: 'center',
                    valign: 'middle'
                }, {
                    field: 'toolName',
                    title: '工装名称',
                    sortable: false,
                    align: 'center',
                    valign: 'middle'
                }, {
                    field: 'toolModel',
                    title: '工装规格',
                    sortable: false,
                    align: 'center',
                    valign: 'middle'
                }, {
                    field: 'equipName',
                    title: '所属设备',
                    sortable: false,
                    align: 'center',
                    valign: 'middle'

                }, {
                    field: 'sendRepairUser',
                    title: '送修人',
                    sortable: false,
                    align: 'center',
                    valign: 'middle'

                }, {
                    field: 'sendRepairDate',
                    title: '送修时间',
                    sortable: false,
                    align: 'center',
                    valign: 'middle'

                }, {
                    field: 'sendRepairCompany',
                    title: '送修公司',
                    sortable: false,
                    align: 'center',
                    valign: 'middle'

                }, {
                    field: 'contact',
                    title: '联系人',
                    sortable: false,
                    align: 'center',
                    valign: 'middle'

                }, {
                    field: 'contactNumber',
                    title: '联系方式',
                    sortable: false,
                    align: 'center',
                    valign: 'middle'

                }, {
                    field: 'pkId',
                    title: 'pkId',
                    visible: false
                }]

        });
    };
    //得到查询的参数
    oTableInit.queryParams = function (params) {
        return {   // 这里的键的名字和控制器的变量名必须一直，这边改动，控制器也需要改成一样的
            size: params.limit,   // 页面大小
            num: (params.offset/params.limit) + 1,  // 页码
            sort: params.sort,
            order: params.order,
            toolCode: $("#toolCode").find("option:selected").text(),
            toolName: $("#toolName").val(),
            toolType: $("#toolType").val(),
            toolModel: $("#toolModel").val(),
            toolStatus: '2',
            equipCode: $("#equipCode").val(),
            type: '2' //委外维修（包含已送修和待维修）
        }
    };
    return oTableInit;
};


var toolRepairDelegationInit = function () {
    return {
        init: function () {
            toolRepairDelegationInit._modalHidden();
            toolRepairDelegationInit._validatorForm();
            toolRepairDelegationInit._repairDelegation();
            toolRepairDelegationInit._refresh();
            toolRepairDelegationInit._save();
            toolRepairDelegationInit._back();
            toolRepairDelegationInit._scrap();
        },
        _refresh: function () {
            //刷新
            $("#refresh2").on("click", function () {
                $('#toolRepairDelegationTable').bootstrapTable('refresh');
            });
        },
        //维修
        _repairDelegation: function () {
            $("#repairDelegation").on('click', function (e) {
                e.preventDefault();
                $('#repairDelegationModal .title').html("送修登记");
                var ids = $.map($('#toolRepairDelegationTable').bootstrapTable('getSelections'), function (row) {
                    return row.pkId;
                });
                var repairStatus = $.map($('#toolRepairDelegationTable').bootstrapTable('getSelections'), function (row) {
                    return row.repairStatus;
                });
                if (ids.length !== 1) {
                    DialogUtil.warning("请选择一行修改");
                    return false;
                }
                //不是待维修
                debugger
                if ("1" !== repairStatus[0]) {
                    DialogUtil.warning("请选择待维修状态工装");
                    return false;
                }
                console.log(ids.toString());
                $("#toolRepairDelegationForm").find("input[name=pkId]").val(ids.toString());
                $("#repairDelegationModal").modal();
            });
        },
        //返厂
        _back: function () {
            $("#back").on("click", function () {
                var ids = $.map($('#toolRepairDelegationTable').bootstrapTable('getSelections'), function (row) {
                    return row.pkId;
                });
                if (ids.length < 1) {
                    DialogUtil.warning("请选择需要返厂的记录");
                    return false;
                }
                var repairStatus = $.map($('#toolRepairDelegationTable').bootstrapTable('getSelections'), function (row) {
                    return row.repairStatus;
                });
                var toolCodes = $.map($('#toolRepairDelegationTable').bootstrapTable('getSelections'), function (row) {
                    return row.toolCode;
                });
                //不是待维修
                if (!"2" === repairStatus[0]) {
                    DialogUtil.warning("请选择已送修状态工装");
                    return false;
                }
                DialogUtil.ok_and_cancel("是否返厂？", function () {
                    $.ajax({
                        url: ctx + '/tool/repair/backFactory/save.mvc',
                        type: "post",
                        dataType: 'json',
                        data: {
                            pkIds: ids.toString(),
                            toolCodes: toolCodes.toString()
                        },
                        success: function (response) {
                            console.log(response);
                            if (response.result === true) {
                                DialogUtil.warning("返厂成功");
                                //$('#toolRepairDelegationTable').bootstrapTable('refresh');
                                toolRepairInit._refreshTable();
                            } else {
                                DialogUtil.error(response.message);
                            }
                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            DialogUtil.error(errorThrown);
                        }
                    });
                }, function () {

                });
            });
        },
        _scrap: function () {
            $("#scrap2").on("click", function () {
                var toolCodes = $.map($('#toolRepairDelegationTable').bootstrapTable('getSelections'), function (row) {
                    return row.toolCode;
                });
                if (toolCodes.length < 1) {
                    DialogUtil.warning("请选择需要报废的记录");
                    return false;
                }
                DialogUtil.ok_and_cancel("是否报废？", function () {
                    $.ajax({
                        url: ctx + '/tool/repair/scrap/save.mvc',
                        type: "post",
                        dataType: 'json',
                        data: {
                            toolCodes: toolCodes.toString()
                        },
                        success: function (response) {
                            console.log(response);
                            if (response.result === true) {
                                DialogUtil.warning("报废成功");
                                //$('#toolRepairDelegationTable').bootstrapTable('refresh');
                                toolRepairInit._refreshTable();
                            } else {
                                DialogUtil.error(response.message);
                            }
                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            DialogUtil.error(errorThrown);
                        }
                    });
                }, function () {

                });
            });
        },
        //表单校验
        _validatorForm: function () {
            $("#toolRepairDelegationForm").bootstrapValidator({
                message: 'This value is not valid',
                live: 'submitted',
                fields: {
                    /*验证*/
                    sendRepairUser: {
                        message: '',
                        validators: {
                            notEmpty: {
                                message: '不能为空'
                            }
                        }
                    },
                    sendRepairDate: {
                        message: '',
                        validators: {
                            notEmpty: {
                                message: '不能为空'
                            }
                        }
                    },
                    sendRepairCompany: {
                        message: '',
                        validators: {
                            stringLength: {
                                max: 40,
                                message: '不能超过40个字符'
                            }
                        }
                    },
                    contact: {
                        message: '',
                        validators: {
                            stringLength: {
                                max: 40,
                                message: '不能超过40个字符'
                            }
                        }
                    },
                    contactNumber: {
                        message: '',
                        validators: {
                            stringLength: {
                                max: 40,
                                message: '不能超过40个字符'
                            }
                        }
                    }
                }
            });
        },
        _save: function () {
            $("#repairDelegationModal .yes").on("click", function (e) {
                $("#repairDelegationModal .yes").attr("disabled", true);
                e.preventDefault();
                $("#toolRepairDelegationForm").data("bootstrapValidator").validate();
                var flag = $("#toolRepairDelegationForm").data("bootstrapValidator").isValid();
                if (!flag) {
                    $("#repairDelegationModal .yes").attr("disabled", false);
                    //未通过验证
                    return false;
                }
                var entity = {};
                entity['pkId'] = $("#toolRepairDelegationForm").find("input[name=pkId]").val();
                entity['contact'] = $("#toolRepairDelegationForm").find("input[name=contact]").val();
                entity['contactNumber'] = $("#toolRepairDelegationForm").find("input[name=contactNumber]").val();
                entity['sendRepairUser'] = $("#toolRepairDelegationForm").find("select[name=sendRepairUser]").val();
                entity['sendRepairCompany'] = $("#toolRepairDelegationForm").find("input[name=sendRepairCompany]").val();
                entity['sendRepairDate'] = $("#toolRepairDelegationForm").find("input[name=requiredDate]").val();
                entity['remark'] = $("#toolRepairDelegationForm").find("input[name=remark]").val();
                console.log(entity);
                $.ajax({
                    url: ctx + '/tool/repair/sendRepair/save.mvc',
                    type: "post",
                    dataType: 'json',
                    data: entity,
                    success: function (response) {
                        if (response.result === true) {
                            DialogUtil.ok("保存成功");
                            //取消
                            $('#repairDelegationModal').modal('hide');
                            $('#toolRepairDelegationTable').bootstrapTable('refresh');
                        } else {
                            DialogUtil.error(response.message);
                        }
                        $("#repairDelegationModal .yes").attr("disabled", false);

                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        $("#repairDelegationModal .yes").attr("disabled", false);
                        console.log(errorThrown);
                        DialogUtil.error("系统错误");
                    }
                });

            });
        },
        _modalHidden: function () {
            //模态框消失清空信息
            $("#repairDelegationModal").on("hide.bs.modal", function () {
                $('#repairDelegationModal input').each(function () {
                    if ($(this).val() !== "") {
                        $(this).val("");
                    }
                });
                $("#sendRepairUser").val(null).trigger("change");
                $('#toolRepairDelegationForm').bootstrapValidator('resetForm', false);
            });
        }
    }
}();